package com.resafety.rtsp2flv.utils;

import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;

@Service
public class ExecuteShellUtil {
private static final Logger log = LoggerFactory.getLogger(ExecuteShellUtil.class);
@Value("${camera.username}")
private String username;
@Value("${camera.password}")
private String password;
@Value("${camera.host}")
private String host;
private Session session;

    public ExecuteShellUtil() {
    }

    private void connect() throws JSchException {
        JSch jsch = new JSch();
        session = jsch.getSession(username, host);
        session.setPassword(password);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        log.info("连接到SFTP成功。host: " + host);
    }


    /**
     *
     * @param command
     * @return 0--成功，1--失败
     * @throws Exception
     */
    public int execCmd(String command) throws Exception {
        int returnCode = -1;
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(System.err);
        BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInputStream()));
        channel.connect();
        StringBuffer buf = new StringBuffer();
        int c = -1;
        while ((c = reader.read()) != -1) {
            buf.append((char) c);
        }
        reader.close();
        if (channel.isClosed()) {
            returnCode = channel.getExitStatus();
        }
        log.info("---给: " + host + " 发送指令:" + command + " 。result:" + returnCode);
        channel.disconnect();
        return returnCode;
    }


}